package com.fourthGroup.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson2.JSON;
import com.fourthGroup.model.Order;
import com.fourthGroup.model.Product;
import com.fourthGroup.model.User;
import com.fourthGroup.service.OrderService;
import com.fourthGroup.service.ProductServiceFeign;
import com.fourthGroup.service.UserServiceFeign;
import com.fourthGroup.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    @Qualifier("ProductServiceFeign")
    private ProductServiceFeign productServiceFeign;
    @Autowired
    private UserServiceFeign userServiceFeign;

    @RequestMapping("/queryall/{oid}")
    public Map<String, Object> queryOrderForAllById(@PathVariable("oid") Long oid) {
        log.info("收到订单编号：{}请求，调用订单查询方法：queryOrderById", oid);
        Map<String, Object> orderMap = new HashMap<>();
        Order order = orderService.queryOrderById(oid);
        orderMap.put("order", order);
        User user = userServiceFeign.queryUserById(order.getUid());
        orderMap.put("user", user);
        log.info("查询成功，所有信息为{}", JSON.toJSONString(orderMap));
        return orderMap;
    }

//    下订单
    @RequestMapping("/product/{pid}")
//    链路模式queryProductById
    @SentinelResource(value = "queryProductById")
    public Order getOrderById(@PathVariable("pid") Integer pid) {

        Product product = productServiceFeign.queryProductById(pid);

//        fallback || fallback factory方式
        if(product.getPid() == -1){
            Order order = new Order();
            order.setOid(-999L);
            order.setPname(product.getPname());
            return order;
        }

        log.info("收到{}号商品下单请求", pid);
        log.info("查询到{}号商品信息，内容为{}", pid, JSON.toJSONString(product));

        Order order = new Order();
        order.setPid(pid);
        order.setUid(1);
        order.setUsername("宋炫磊");
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        order.setStatus(1);
        orderService.addOrder(order);
        log.info("创建订单成功，订单信息为{}", JSON.toJSONString(order));
        return order;
    }
//    查询订单
    @RequestMapping("/query/{oid}")
    public Order queryOrderById(@PathVariable("oid") Long oid) {
        log.info("收到订单编号：{}请求，调用订单查询方法：queryOrderById", oid);
        Order order = orderService.queryOrderById(oid);
        log.info("订单查询成功，订单信息为：{}", JSON.toJSONString(order));
        return order;
    }

//    更新订单状态*
    @RequestMapping("/updatestatus/{oid}")
    public Order updateOrderStatusById(@PathVariable("oid") Long oid) {
        log.info("收到订单编号：{}请求，调用更新订单状态方法：updateOrderStatus", oid);
        orderService.updateOrderStatus(oid);
        Order order = orderService.queryOrderById(oid);

        log.info("订单状态更新成功，订单信息为{}", JSON.toJSONString(order));
        return order;
    }

//    查询对应商品信息
    @RequestMapping("/queryproduct/{oid}")
    public Product queryProductById(@PathVariable("oid") Long oid) {
        log.info("收到编号{}订单请求，调用订单查询方法queryOrderById()",oid);
        Order order = orderService.queryOrderById(oid);
        if (order != null) {
            Product product = productServiceFeign.queryProductById(order.getPid());
            log.info("订单查询成功，订单信息为：{}", JSON.toJSONString(order));
            return product;
        } else {
            log.info("订单查询失败，订单编号无效");
            return null;
        }
    }

    @PostMapping
    public Result<Order> createOrder(@RequestBody Order order) {
        log.info("创建订单: {}", order);
        return orderService.createOrder(order);
    }

    @GetMapping("/{oid}")
    public Result<Order> getOrder(@PathVariable Long oid) {
        log.info("查询订单: {}", oid);
        return orderService.getOrder(oid);
    }
    
    /**
     * 应用优惠券到订单
     */
    @PostMapping("/applyCoupon")
    public Result<Double> applyCoupon(@RequestParam("orderId") String orderId, 
                                     @RequestParam("couponId") Long couponId) {
        log.info("应用优惠券到订单: orderId={}, couponId={}", orderId, couponId);
        return orderService.applyCoupon(orderId, couponId);
    }
}
